﻿using System;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Web.Script.Serialization;
using System.Web.UI;
using EPiServer.Framework.DataAnnotations;
using EPiServer.Web;
using EPiServer.Web.PropertyControls;

namespace OpenWaves.EPiServer.BrightcoveVideoCloudProperty
{
    [TemplateDescriptor(TagString = VideoCloudProperty.UIHint)]
    public class PropertyVideoCloudControl : PropertyUrlControl, IRenderTemplate<global::EPiServer.Url>
    {
        protected override void Render(HtmlTextWriter writer)
        {
            if (this.IsNull || string.IsNullOrWhiteSpace(this.PropertyData.ToString()))
                return;

            var width = GetIntegerValue("VideoWidth", 640);
            var height = GetIntegerValue("VideoHeight", 480);

            writer.AddAttribute(HtmlTextWriterAttribute.Src, "http://admin.brightcove.com/js/BrightcoveExperiences.js");
            writer.AddAttribute(HtmlTextWriterAttribute.Type, "text/javascript");
            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            writer.Write(
                @"window.onload = function () { BCL.addPlayer(BCL.singlePlayerTemplate, BCL.singlePlayerData); };");
            writer.RenderEndTag();

            writer.RenderBeginTag(HtmlTextWriterTag.Script);
            var serializer = new JavaScriptSerializer();
            var value = serializer.Deserialize<VideoCloudValue>(this.PropertyData.ToString());
            if (value == null)
                return;

            var player = VideoCloudService.Configuration.PlayersList.FirstOrDefault();
            if (string.IsNullOrWhiteSpace(value.SelectedPlayer) == false)
            {
                player =
                    VideoCloudService.Configuration.PlayersList.FirstOrDefault(
                        p => p.PlayerId.Equals(value.SelectedPlayer, StringComparison.OrdinalIgnoreCase));
            }
            if (player == null || string.IsNullOrWhiteSpace(value.SelectedItem))
                return;

            writer.Write(
                @"var BCL = {{}}; BCL.singlePlayerData = {{'playerID': '{0}', 'playerKey': '{1}', 'width': '{2}', 'height': '{3}','videoID': '{4}'}};",
                player.PlayerId, player.PlayerKey, width, height, value.SelectedItem);
            writer.RenderEndTag();

            writer.Write(Resources.VideoEmbed);

            writer.AddAttribute(HtmlTextWriterAttribute.Id, "VideoContainer");
            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ow-video-container");
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.RenderEndTag();
        }

        private int GetIntegerValue(string key, int defaultValue)
        {
            if (!RenderSettings.ContainsKey(key))
            {
                return defaultValue;
            }

            int value;
            if (int.TryParse(RenderSettings[key] as string, NumberStyles.Integer, CultureInfo.InvariantCulture,
                             out value))
            {
                return value;
            }
            return defaultValue;
        }
    }

    public class VideoCloudValue
    {
        [DataMember(Name = "selectedItem")]
        public string SelectedItem { get; set; }

        [DataMember(Name = "selectedPlayer")]
        public string SelectedPlayer { get; set; }
    }
}